let {Service} = require('egg');


class VoteService extends Service{
    async create(title,desc,endTime,isName,createUser,createTime,items){
        let vote =  await this.app.mysql.query('insert into vote_list (title,con,endTime,isName,createUser,createTime) values (?,?,?,?,?,?)',[title,desc,endTime,isName,createUser,createTime]);
        let {insertId} = vote; //投票的id
        let arr = items.split(',');
        for(let i = 0;i<arr.length;i++){
            await this.app.mysql.query('insert into vote_item (text,num,vid) values (?,?,?)',[arr[i],0,insertId])
        }
    }
    //投票
    async vote(vid,id,username){
        //投票人员的表  投票选项的表
        await this.app.mysql.query('insert into vote_users (vid,username) values (?,?)',[vid,username])
        let voteNum = await this.app.mysql.query('select num from vote_item where id=?',[id]);
        // console.log(num1)
        let num = voteNum[0].num+1;
        console.log(num)
        await this.app.mysql.query('update vote_item set num=? where id=?',[num,id])

    }

    //我创建的投票
    async myCreate(username){
        // console.log(username);
        let list = await this.app.mysql.query('select * from vote_list where createUser=?',[username])
       

        for(let i=0;i<list.length;i++){
            let vid = list[i].id;
            list[i].items = await this.app.mysql.query('select * from vote_item where vid=?',[vid]);
        }

        console.log(list);
        return list
    }

    //我参与的投票
    async joinVote(username){
        //1.我参与投票的所有vid
        // let vids = await this.app.mysql.query('select vid from vote_users where username=?',[username])
        
        let list = await this.app.mysql.query('select * from vote_list where id in (select vid from vote_users where username=?)',[username])
        for(let i=0;i<list.length;i++){
            let vid = list[i].id;
            list[i].items = await this.app.mysql.query('select * from vote_item where vid=?',[vid]);
        }
        return list
    }

    //获取投票列表
    async votelist(){
        let list = await this.app.mysql.query('select * from vote_list')
        for(let i=0;i<list.length;i++){
            let vid = list[i].id;
            list[i].items = await this.app.mysql.query('select * from vote_item where vid=?',[vid]);
            let users = await this.app.mysql.query('select username from vote_users where vid=?',[vid]);
            console.log(users);
            list[i].voteUsers = users.map(item => item.username)
        }

        return list
    }

    /**
     * [
     *  {
     *      title:'',
     *      con:'',
     *      items:[
     *          {
     *              text:dddd,
     *              num:xx 
     *          },
     *             ....    
     *      ],
     *      createTime：’‘，
     *      
     *  }
     * ]
     * 
    */
}

module.exports = VoteService